package com.koron.css2.baseConfig.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.CostDetailBean;
import com.koron.css2.baseConfig.bean.CostDetailLadderBean;
import com.koron.css2.baseConfig.mapper.CostDetailMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

/**
 * 费用信息-添加
 * @author 李攀
 */
public class CostDetailAdd implements ServerInterface {

	private static Logger logger = LogManager.getLogger(CostDetailAdd.class);

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		try {
			CostDetailMapper mapper = factory.getMapper(CostDetailMapper.class);
			CostDetailBean bean = JsonUtils.objectToPojo(req.getData(), CostDetailBean.class);
			// 校验字段重复
			if (mapper.check("detail_name", bean.getDetailName()) > 0) {
				return MessageBean.create(Constant.ILLEGAL_PARAMETER, "明细名称：" + bean.getDetailName() + "的信息已存在。",
						void.class);
			}
			bean.setCostDetailId(new ObjectId().toHexString());
			bean.setCreateName(userInfo.getUserInfo().getName());
			bean.setCreateTime(CommonUtils.getCurrentTime());
			List<CostDetailLadderBean> ladderlist = bean.getLadderlist();
			if (ladderlist.size() == 0 || ladderlist==null) {
				return MessageBean.create(Constant.ILLEGAL_PARAMETER, "所选阶梯内容不能为空！", void.class);
			}
			for (CostDetailLadderBean ladderBean : ladderlist) {
				if(ladderBean.getBeginWater()==null || ladderBean.getCoefficient()==null || ladderBean.getEndWater()==null || ladderBean.getLadderBeginMoney()==null ||ladderBean.getPrice()==null ) {
					return MessageBean.create(Constant.ILLEGAL_PARAMETER, "价格阶梯填写内容不能为空！", void.class);
				}
				ladderBean.setCostDetailLadderId(new ObjectId().toHexString());
				ladderBean.setCostDetailId(bean.getCostDetailId());
			}
			mapper.insertCostDetail(bean);
			mapper.insertLadderList(ladderlist);
		} catch (Exception e) {
			logger.error("非法参数", e);
			return MessageBean.create(Constant.ILLEGAL_PARAMETER, "非法参数", void.class);
		}
		return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);
	}
}